<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" pageName="分站类型">
      <template v-slot:opraCurdBtn1="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row)">查看</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <el-button class="btn" type="primary" link @click="addBtn('mul')">
          <el-icon style="margin-right: 2px;">
            <svg-icon class-name="search-icon" icon-class="addtotal" />
          </el-icon>新增
        </el-button>
        <el-button class="btn" type="primary" link @click="deleteBtn('mul')">
          <el-icon>
            <DeleteFilled />
          </el-icon>删除
        </el-button>
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto" v-model="state.addModal"
        resize :mask="true">
        <template #title>
          <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="类型名称" prop="stationTypeName">
                    <el-input v-model="state.formData.stationTypeName" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="分站模式" prop="stationModelId">
                    <el-select clearable filterable v-model="state.formData.stationModelId" placeholder="请选择"
                      @change="stationModelChange">
                      <el-option v-for="item in state.stationmodelList" :key="item.id" :label="item.stationModelName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="输入口数量" prop="stationInNum">
                    <el-select clearable filterable v-model="state.formData.stationInNum" placeholder="请选择">
                      <el-option v-for="item in state.stationInNumList" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="输出口数量" prop="stationOutNum">
                    <el-select clearable filterable v-model="state.formData.stationOutNum" placeholder="请选择">
                      <el-option v-for="item in state.stationOutNumList" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="分站类型图片上传" prop="imagePath">
                    <el-upload v-model:file-list="state.fileList" action  :before-upload="beforeUpload"
                      :http-request="uploadHttpRequestAdd" ref="upload"
                      list-type="picture" :on-preview="handlePictureCardPreview">
                      <el-button type="primary">
                        <svg-icon class-name="search-icon" icon-class="photo" />上传图片</el-button>
                      <template #tip>
                        <div class="el-upload__tip">
                          上传图片支持jpg/png等，大小不超过 500kb
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <img v-if="state.formData.imagePath" style="width:60px;height:60px;"
                    :src="state.formData.imagePath" />
                </el-col> -->
              </el-row>
            </el-form>
            <div class="form_footer">
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="submitForm">
                确定
              </el-button>
            </div>
          </div>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 详情 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="40%" close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="dot" /><span>分站类型详情</span></h4>
      </template>
      <p class="drawer_sub_title">
        <span class="sub_title_line">基础信息</span>
      </p>
      <div>
        <el-row :gutter="20"
          style="background: rgba(91, 109, 128, 0.04);display: flex;align-items: center;padding: 20px 0;">
          <el-col :span="8" style="text-align: center;">
            <div class="img_box">
              <img v-if="state.formData.imagePath!=null" :src="state.formData.imagePath" alt="" />
              <img v-else src="@/assets/images/noimg.png" />
            </div>
            <span>{{ state.formData.stationTypeName }}</span>
          </el-col>
          <el-col :span="16">
            <el-row :gutter="20">
              <el-col :span="7">
                <p>分站模式</p>
                <p>{{state.formData.stationModelName}}</p>
              </el-col>
              <el-col :span="9">
                <p>输入口数量/输出口数量</p>
                <p>{{state.formData.stationInNum}}/{{state.formData.stationOutNum}}</p>
              </el-col>
              <el-col :span="8">
                <p>引用数量</p>
                <p>{{state.formData.quoteNum}}</p>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:10px;">
          <el-col :span="24">
            <p class="drawer_sub_title">
              <span class="sub_title_line">基础信息</span>
            </p>
          </el-col>
          <el-col :span="24">
            <p class="fsc">
              <span class="wn">编号</span>
              <el-input style="width:200px;margin:0 10px;" v-model="state.options1.queryList.stationCode" clearable
                placeholder="请输入">
              </el-input>
              <el-button type="primary" @click="yinyonClick">查询</el-button>
              <el-button type="info" @click="reset">重置</el-button>
            </p>
            <vxe-table :loading="loading" height="340" :data="state.formData.stationBasicDtoList" border="inner">
              <vxe-column type="seq" :width="55" title="序号"></vxe-column>
              <vxe-column v-for="(item,index) in state.options1.tableheads" :field="item.field" :title="item.title"
                :params="{name:item.name}" :width="item.width?item.width:''" :key="index">
              </vxe-column>
              <vxe-column title="操作">
                <template #default="{row}">
                  <el-button type="primary" link size="small" @click="btnClick(row)">跳转分站详情</el-button>
                </template>
              </vxe-column>
            </vxe-table>
          </el-col>
        </el-row>

      </div>
    </el-drawer>
    <el-dialog v-model="state.dialogVisiblepictureCardPreview">
        <img :src="state.dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import {
    computed,
    reactive
  } from "vue";
  import {
    table_headers
  } from '@/components/commonCom/table_headers';
  import axios from "@/utils/request"
  import usePagesStore from '@/store/modules/pages'
  import {
    getsubstationmodel,
    fileupload
  } from '@/api/config'
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore()
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP
  components: {
    list_controller
  }
  const upload = ref(null)
  let state = reactive({
    fileList:[],
    dialogVisiblepictureCardPreview:false,
    dialogImageUrl:'',
    options: {
      tableheads: computed(() => table_headers.stationType),
      queryList: {
        dropdownUrl: '',
        querys: [{
          field: 'stationTypeName',
          title: '类型名称',
          type: 'input',
          binddata: ''
        }, {
          field: 'stationModelId',
          title: '分站模式',
          type: 'select',
          binddata: '',
          options: [],
        }],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/substation/type/search',
      delUrl: '/substation/type/deleteStation',
      addUrl: '/substation/type/addStation',
      descUrl: '/substation/type/searchStation/',
      editUrl: '/substation/type/editStation',
    },
    // 表单
    addModal: false,
    modalTitle: '新增分站类型',
    drawerShow: false,
    formRef: null,
    formData: {},
    rules: {
      stationTypeName: [{
        required: true,
        message: '请输入类型名称',
        trigger: 'blur'
      }],
      stationModelId: [{
        required: true,
        message: '请输入通风类型',
        trigger: 'change'
      }],
      stationInNum: [{
        required: true,
        message: '请选择传感器编号',
        trigger: 'change'
      }],
      stationOutNum: [{
        required: true,
        message: '请输入报警浓度',
        trigger: 'change'
      }]
    },
    editId: undefined,
    stationmodelList: [],
    stationInNumList: [],
    stationOutNumList: [],
    options1: {
      tableheads: computed(() => table_headers.quoteStation),
      queryList: {
        autoSearch: true,
        dropdownUrl: '',
        stationCode: '',
        stationTypeId: '',
        querys: [{
          field: 'stationCode',
          title: '编号',
          type: 'input',
          binddata: ''
        }],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/substation/type/quote'
    },
  })
  // 查看按钮
  function lookBtn(row) {
    state.drawerShow = true
    axios.post(state.options.descUrl + row.id).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        state.options1.queryList.stationTypeId = res.data.id
      }
    })

  }

  function btnClick(row) {
    router.push({
      path: '/cspz/netConfig/net_pointConfig',
      query: {
        id: row.id,
        stationCode: row.stationCode
      }
    })
  }

  function yinyonClick() {
    axios.post('/substation/type/quote', {
      stationTypeId: state.options1.queryList.stationTypeId,
      stationCode: state.options1.queryList.stationCode
    }).then(res => {
      if (res.code == 200) {
        state.formData.stationBasicDtoList = res.data.list
      }
    })
  }

  function reset() {
    state.options1.queryList.stationCode = ''
    axios.post('/substation/type/quote', {
      stationTypeId: state.options1.queryList.stationTypeId,
      stationCode: state.options1.queryList.stationCode
    }).then(res => {
      if (res.code == 200) {
        state.formData.stationBasicDtoList = res.data.list
      }
    })
  }
  // 新增按钮
  function addBtn(row) {
    state.modalTitle = '新增分站类型'
    state.addModal = true
    state.formData = {}
    state.editId = undefined
    state.fileList=[]
  }
  function LastStr(str) {
    if(str){
      let index = str.lastIndexOf("\/");
      str = str.substring(index + 1, str.length);
      return str;
    }
  }
  // 编辑按钮
  function editBtn(row) {
    state.modalTitle = '编辑地点类型'
    state.addModal = true
    axios.post(state.options.descUrl + row.id).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        state.fileList=[{name:LastStr(state.formData.imagePath),url:state.formData.imagePath}]
        state.editId = res.data.id
      }
    })
  }

  function deleteBtn(row) {
    let ids = []
    if (row != 'mul') {
      ids = [row.id]
    } else {
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        proxy.$modal.msgSuccess('请先勾选所要删除数据!');
      }
    }
    if (ids.length > 0) {
      axios.post(state.options.delUrl, ids).then(res => {
        if (res.code == 200) {
          proxy.$refs['zujianname'].getData()
          state.addModal = false
          proxy.$modal.msgSuccess(res.msg);
          store.records = []
        }
      })
    }

  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        if (state.editId) {
          state.formData.id = state.editId
          axios.post(state.options.editUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        } else {
          axios.post(state.options.addUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        }
      }
    })
  }
  function cancel() {
    state.addModal = false
  }

  function getsubstationmodelList() {
    let arr = []
    getsubstationmodel().then(res => {
      state.stationmodelList = res.data
      state.stationmodelList.forEach(item => {
        arr.push({
          value: item.id,
          label: item.stationModelName
        })
        state.options.queryList.querys[1].options = arr
      })
    })
  }

  function stationModelChange(val) {
    state.stationmodelList.forEach(item => {
      if (item.id == val) {
        state.stationInNumList = item.stationInNumList
        state.formData.stationInNum = item.stationInNumList[0]
        state.stationOutNumList = item.stationOutNumList
        state.formData.stationOutNum = item.stationOutNumList[0]
      }

    })
  }
  // getsubstationmodelList()
  const fileType = [
    "jpg", "png", "gif", "jpg", "jpeg"
  ] // 允许的文件类型
  const uploadHttpRequestAdd = (data) => {
    upload.value.clearFiles();
    const formData = new FormData();
    formData.append("file", data.file);
    fileupload(formData).then(res => {
      state.formData.imagePath = previewHttps + res.fileName
      state.fileList.push({name:res.originalFilename,url:state.formData.imagePath})
      proxy.$modal.msgSuccess(res.msg);
    })
  }
  const beforeUpload = (file) => { //上传前的钩子
    if (file.type != "" || file.type != null || file.type != undefined) {
      //截取文件的后缀，判断文件类型
      const FileExt = file.name.replace(/.+\./, "").toLowerCase();
      // 计算文件的大小
      const isLt5M = file.size / 1024 < 500; //这里做文件大小限制
      //如果大于500kb
      if (!isLt5M) {
        proxy.$modal.msgWarning("上传文件大小超过限制!");
        upLoading.value = 0
        return false;
      }
      //如果文件类型不在允许上传的范围内
      if (fileType.includes(FileExt)) {
        return true;
      } else {
        proxy.$modal.msgWarning("上传文件格式不正确!");
        upLoading.value = 0
        return false;
      }
    }
  }
  function handlePictureCardPreview(uploadFile) {
    state.dialogVisiblepictureCardPreview = true
    state.dialogImageUrl = uploadFile.url
  }
</script>
<style lang="scss" scoped>
  ::v-deep .el-drawer {
    .querycss {
      .fsc {
        &:nth-child(2) {
          display: none;
        }
      }
    }

    .table_box {
      .fsc {
        display: none;
      }
    }
  }
</style>